//
//  AppDelegate.m
//  FloatClouds
//
//  Created by 黄威 on 16/8/25.
//  Copyright © 2016年 黄威. All rights reserved.
//

#import "AppDelegate.h"
#import "MaintabController.h"
#import "TAMacro.h"
#import "iflyMSC/IFlyMSC.h"
#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"

#define WIDTH self.window.frame.size.width
#define HEIGHT self.window.frame.size.height
BOOL isOut = NO;
@interface AppDelegate ()<UIScrollViewDelegate>
@property (nonatomic, retain) UIView *backView;
@property (nonatomic, strong) UIPageControl *page;
@property(nonatomic, strong) BaseTabController *tabBarController;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

#pragma mark - 添加夜间模式标识
    
    NSUserDefaults *nightIsOn = [NSUserDefaults standardUserDefaults];
    
    NSString *isOn = [nightIsOn objectForKey:@"night"];
    
    if (isOn.length == 0) {
        
        NSUserDefaults  *nightIsOn = [NSUserDefaults standardUserDefaults];
        
        NSString *isOn = @"0";
        
        [nightIsOn setObject:isOn forKey:@"night"];
        
    }
    
    
    [NSThread sleepForTimeInterval:0.5];
    
#pragma mark - 创建Windows
    
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    MaintabController *mainTabController = [[MaintabController alloc]init];
    
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,([UIScreen mainScreen].bounds.size.width), 49)];
    
  
    
    if ([isOn isEqualToString:@"0"] || isOn.length == 0) {
        
         self.backView.backgroundColor = [UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1];
        
    }else if([isOn isEqualToString:@"1"]){
        
        self.backView.backgroundColor = [UIColor colorWithRed:93/255.0 green:92/255.0 blue:101/255.0 alpha:1];
        
    }
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                      selector:@selector(ON)
                                                          name:@"NIGHTON"
                                                        object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                      selector:@selector(OFF)
                                                          name:@"NIGHTOFF"
                                                        object:nil];

    
    [mainTabController.tabBar insertSubview:self.backView atIndex:0];
    mainTabController.tabBar.opaque = YES;
    
    self.window.rootViewController = mainTabController;
    
    
    
 
    
    //显示SDK的版本号
  //  NSLog(@"verson=%@",[IFlySetting getVersion]);
    
    //设置sdk的log等级，log保存在下面设置的工作路径中
    [IFlySetting setLogFile:LVL_ALL];
    
    //打开输出在console的log开关
    [IFlySetting showLogcat:NO];
    
    //设置sdk的工作路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    [IFlySetting setLogFilePath:cachePath];
    
    //创建语音配置,appid必须要传入，仅执行一次则可
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",APPID_VALUE];
    
    //所有服务启动前，需要确保执行createUtility
    [IFlySpeechUtility createUtility:initString];
    
    
    
    
    
#pragma mark - JPUSH
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    //Required
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    //CHANNEL指明应用程序包的下载渠道，为方便分渠道统计，具体值由你自行定义，如：App Store。
    //APP_KEY填写[管理Portal上创建应用](https://www.jpush.cn/apps/new)后自动生成的AppKey值。请确保应用内配置的 AppKey 与第1步在 Portal 上创建应用后生成的 AppKey 一致。
    //APS_FOR_PRODUCTION1.3.1版本新增，用于标识当前应用所使用的APNs证书环境。
    //0 (默认值)表示采用的是开发证书，1 表示采用生产证书发布应用。
    //注：此字段的值要与Build Settings的Code Signing配置的证书环境一致。
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
    
    
    [self makeLaunchView];
    [self addPage];
    

#pragma mark - UmengShare

    [UMSocialData setAppKey:@"57e3a06a67e58e9ed90006fa"];
    //设置友盟社会化组件appkey
    
    //设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:@"wx91592e5ae8c86541" appSecret:@"078744c78949ef9a2c4b6a8b3c954246" url:@"http://www.umeng.com/social"];
    //设置手机QQ 的AppId，Appkey，和分享URL，需要#import "UMSocialQQHandler.h"
    [UMSocialQQHandler setQQWithAppId:@"1105712228" appKey:@"AnIlkTfLXXxm6yNJ" url:@"http://www.umeng.com/social"];

    

    
    return YES;


}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
    }
    return result;
}

-(void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    NSLog(@"My token is: %@", deviceToken);
    
}




- (void)makeLaunchView {
    
    
    // 数组内存放的是我要显示的引导页图片
    NSArray *arr = [NSArray arrayWithObjects:@"01", @"02", @"03", @"04", nil];
    // 通过scrollView将这些图片添加在上面， 从而达到滚动这些图片
    UIScrollView *scr = [[UIScrollView alloc] initWithFrame:self.window.bounds];
    scr.contentSize = CGSizeMake(WIDTH * arr.count, HEIGHT);
    // 分页效果
    scr.pagingEnabled = YES;
    // 监听滑动
    scr.delegate = self;
    [self.window addSubview:scr];
    for (int i = 0; i < arr.count; i++) {
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(i * WIDTH, 0, WIDTH, HEIGHT)];
        img.image = [UIImage imageNamed:arr[i]];
        [scr addSubview:img];
    }
    
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)addPage {
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(WIDTH / 2 - 50, HEIGHT - 60, 100, 40)];
    // 当前页数
    self.page.currentPage = 0;
    self.page.numberOfPages = 4;
    [self.window addSubview:self.page];
}
// scrollView的协议方法
// 第一类： 监听滚动 让图控制点：把偏移量转化contentOffset为点currentPage
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 这里是在滚动的时候判断我滚动到那张图片了， 如果滚动到了最后一张图片， 那么 往下滑动就应该进入主页面， 我这里是利用偏移量来判断的， 一共四张图片， 所以当图片全部滑动完后， 又向后多滑动一段距离的时候就坐下一个动作
    if (scrollView.contentOffset.x > 3 * WIDTH + 30) {
        isOut = YES;
        // 这是我声明的一个全局变量BOOL类型，初始化为no，当到达我需要的条件将值改为yes
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger index = scrollView.contentOffset.x / scrollView.frame.size.width;
    // 让点控制图： 把currentPage 转化为contentOffset
    self.page.currentPage = index;
    // 判断isOut为真 就要进入主界面了
    if (isOut) {
        // 在这里添加一个动画（根据个人喜好）
        [UIView animateWithDuration:1.5 animations:^{
            scrollView.alpha = 0;//让scrollView 渐变消失
        } completion:^(BOOL finished) {
            [scrollView removeFromSuperview];// 将scrollview移除
            self.page.hidden = YES;
        }];
    }
}
- (void)ON{

    self.backView.backgroundColor = [UIColor colorWithRed:93/255.0 green:92/255.0 blue:101/255.0 alpha:1];


}

- (void)OFF{
    //93 92 101
    self.backView.backgroundColor = [UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1];

}

- (void)dealloc{
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NIGHTON" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NIGHTOFF"object:nil];
    
    
}

@end
